//
//  MyMD5.m
//  GoodLectures
//
//  Created by yangshangqing on 11-10-11.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "MyMD5.h"
#import "CommonCrypto/CommonDigest.h"

@implementation MyMD5

+(NSString *) md5: (NSString *) inPutText 
{
    const char *cStr = [inPutText UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, strlen(cStr), result);
    
    return [[NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
             result[0], result[1], result[2], result[3],
             result[4], result[5], result[6], result[7],
             result[8], result[9], result[10], result[11],
             result[12], result[13], result[14], result[15]
             ] lowercaseString];
}


+(NSString *) RSAPrivateEncrypt:(NSString *)privateCode modelStr:(NSString *)modelStr sourceStr:(NSString *)sourceStr{
	
	//NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	
	//srand(time(NULL));
	
	NSStringEncoding enc = NSUTF8StringEncoding;
	
    BIGNUM *modulus = NULL;
	
	const char *kModulus = [privateCode cStringUsingEncoding:enc];
    //	printf("modulus %s\n",kModulus);
	BN_dec2bn(&modulus,kModulus);
	BIGNUM *exponent = NULL;
	const char *kExponent = [modelStr cStringUsingEncoding:enc];
	BN_dec2bn(&exponent,kExponent);
	
	NSData *data = [sourceStr dataUsingEncoding: enc];
	const unsigned char *plain =  [data bytes];
	BIGNUM *plainnum = BN_new();
	
	BN_bin2bn(plain,[data length] , plainnum);
    //	printf("\nbig number %s\n",BN_bn2dec(plainnum));
	BIGNUM *r = BN_new ();
	BN_CTX *ctx = BN_CTX_new();
	BN_mod_exp(r, plainnum,exponent,modulus,ctx);
	char *result = BN_bn2dec(r);
//	int sizetemp = strlen(result);
	
    //	printf("\nresult %s\n",result);
	NSString *resultStr = [NSString stringWithCString:result encoding:NSUTF8StringEncoding];
	//NSString *resultStr = [NSString stringWithCharacters:(const unichar *)result length:sizetemp];
	//NSLog(resultStr);
	BN_free(plainnum);
	BN_free(r);
	BN_CTX_free(ctx);
	// [pool drain];
	
    return resultStr;
	//return nil;
}

@end
